package org.cdc;

import com.alibaba.fastjson.JSONObject;
import org.cdc.mre.manager.*;

import java.io.*;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.util.*;
import java.util.logging.Logger;

public class Main {
    public static void main(String[] args) throws IOException {
        long starts = System.currentTimeMillis();
        Map<String,String> args1 = ArgsManager.format(args);
        if (args1.containsKey("-?")){
            System.out.println("用法: mre [-pack zip文件路径] -json <json路径> -resource <资源路径> [-output 输出路径] [-filter 正则表达式]");
            return;
        }
        if (args1.containsKey("-filter")){
            Main.filter = args1.get("-filter");
        }
       if (!args1.containsKey("-output")){
           exportResource(args1.get("-json"),args1.get("-resource"),new File("assets").getAbsolutePath());
       } else {
            exportResource(args1.get("-json"),args1.get("-resource"),args1.get("-output"));
        }
       if (args1.containsKey("-pack")){
           Logger.getGlobal().info("开始打包");
           pack(args1.get("-pack"));
       }
        long ends = System.currentTimeMillis();
        Logger.getGlobal().info(String.format("程序执行完成,总共%d个文件,已经提取了%d个,忽略了%d个,用时%dms,提取文件大小%s,",totalFiles,FileExported,totalFiles-FileExported,ends-starts, FileSizeManager.toSizeString(maxSize)));
    }
    public static void exportResource(String jsonPath,String assetsPath,String exportPath) throws IOException {
        init(jsonPath,assetsPath,exportPath);
        exportResource();
    }
    public static String filter;
    private static String jsonPath;
    private static String assetsPath;
    private static String exportPath;
    private static Map<String, File> index;
    private static JSONObject jsonObject;
    private static long maxSize;
    private static long totalFiles;
    private static long FileExported;
    private static void init(String jp,String ap,String ep) throws IOException {
        //初始化所有的参数
        Main.jsonPath = jp;
        Main.assetsPath = ap;
        Main.exportPath = ep;
        File jsonpath = new File(jp);
        File assetPath = new File(ap);
        File exportsPath = new File(ep);
        if (!(jsonpath.exists() && assetPath.exists() && jsonpath.isFile())) { // 检查存在性与相关所需的路径的类型
            throw new FileNotFoundException(String.format("json路径:%s 存在:%s 是否为文件:%s\nasset路径:%s 存在:%s\n输出路径:%s",jsonPath,jsonpath.exists(),jsonpath.isFile(),assetsPath,assetPath.exists()));
        }
        if (!exportsPath.exists()){ // 如果输出路径不存在,那么自行创建
            exportsPath.mkdirs();
        }
        Logger.getGlobal().info(String.format("JSON索引路径为%s,资源路径为%s,检查完毕,即将输出资源文件于%s",jp,ap,ep));
        Logger.getGlobal().info("开始构建资源路径索引");
        index = IndexManager.makeIndex(assetPath); //构建索引
        Logger.getGlobal().info("索引构建成功");
        Logger.getGlobal().info("开始读取json索引文件");
        jsonObject = JSONManager.compileJSONObjectForFile(Main.jsonPath); //读取json文件
        Logger.getGlobal().info("读取成功");
    }
    private static void exportResource() throws IOException {
        Logger.getGlobal().info("初始化完毕,开始输出文件");
        JSONObject objects = jsonObject.getJSONObject("objects");
        for (Map.Entry<String,Object> entry: objects.entrySet()){
            //得到相关的信息
            totalFiles++;
            String path =entry.getKey(); // 得到了文件的相对路径,之后与输出路径合并成为资源输出路径
            File pt= new File(path);
            if (Main.filter != null && !pt.getName().matches(Main.filter)) continue;
            FileExported++;
            JSONObject jsonObject = (JSONObject) entry.getValue();
            String hash = jsonObject.getString("hash");
            long size = jsonObject.getLong("size");
            Main.maxSize += size;
            //根据hash码映射索引File,我**Mojang(我爱Mojang)
            File need_file = index.get(hash);
            File resourceExport = new File(exportPath.replaceAll(File.pathSeparator,"/")+"/"+path);
            Logger.getGlobal().info(String.format("正在输出文件%s",resourceExport.getAbsolutePath()));
            File parentFile = resourceExport.getParentFile();
            Logger.getGlobal().info(String.format("母路径%s",parentFile.getAbsolutePath()));
            if (!(parentFile.exists())) {
                    parentFile.mkdirs();
            }
            try {
                Files.copy(need_file.toPath(),resourceExport.toPath());
            } catch (FileAlreadyExistsException e) {
                Logger.getGlobal().info("文件"+resourceExport.getName()+"已经存在,跳过");
            }
        }
    }
    private static void pack(String zipPath) throws IOException {
        ZipManager.pack(zipPath,exportPath);
        Logger.getGlobal().info("打包完成");
    }
}
